package com.intel.factorytest.activity;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import com.intel.factorytest.FactoryTest;
import com.intel.factorytest.R;
import com.intel.factorytest.application.MATApplication;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.constants.PropertiesConstants;
import com.intel.factorytest.log.LogWriter;
import com.intel.factorytest.util.PropertiesUtil;

public class BaseActivity extends Activity {
    private static final String TAG = "BaseActivity";
    protected static final String TEST_ITEM = "test_item";
    protected static final String ITEM_NAME = "item_name";
    protected static final String TEST_ITEM_RESULT = "test_item_result";
    public static final String TEST_LOG_RESULT = "log_result";
    protected boolean is_pass = false;
    protected int test_pos = 0;
    protected String itemName;
    protected int orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    // is pcba test
    protected String sys_service_for_pcba ="SYSTEM_SERVICE_FOR_PCBA_TEST";
    protected boolean isPcba = false;
    // is system test
    protected String sys_service ="SYSTEM_SERVICE_TEST";
    protected boolean isSystemTest = false;
    
    public static String EXTERNAL_CARD_PATH;
    public static String INTERNAL_CARD_PATH;
    
    protected int widthScreen = 0;
    protected int heightScreen = 0;
    
    public int lenX;
    public int lenY;
    
    protected Button mSucBtn;
    protected Button mFailBtn;
    protected Button mRepeatBtn;
    
    // logger
    protected String logFileName;
    protected LogWriter.TestCase tc;
    protected boolean isLogged = false;
    
    // output stream
    protected FileOutputStream out;
    
    // product type [0]:Baytrail [1]:SoFIA
    protected int productType = 1;
    
    // Locale
//    private Locale locale;
    protected boolean mItemTestFinish = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        updateConfiguration();//update language
        initOrientation();
        initScreenSize();
        initLenXY();
//        Log.d(TAG, "1 initTestCase");
        initTestCase();
//        Log.d(TAG, "2 initTestCase");
//        changeLanguage(locale);
//        super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }
    
    protected void initOrientation() {
        Intent intent = getIntent();
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        test_pos = intent.getIntExtra(TEST_ITEM, -1);
        isPcba = intent.getIntExtra(sys_service_for_pcba, 0) == 1 ? true : false;
        isSystemTest = intent.getIntExtra(sys_service, 0) == 1 ? true : false;
        itemName = intent.getStringExtra(ITEM_NAME);
        logFileName = intent.getStringExtra(LogWriter.LogFileNameTag);
        isPcba = false;
        isSystemTest = true;
//        locale = (Locale) intent.getExtra("Locale");
//        out = openFileOutput(logFileName, Context.MODE_PRIVATE);
        
        
        // new feature: V2.1.8
//        Log.d(TAG, "1 initProductType");
//        initProductType();
//        Log.d(TAG, "2 initProductType");
        
//        MATApplication app = (MATApplication) getApplication();
//        if (app.getScreenOrientationDefine()){
//            super.setRequestedOrientation(app.getScreenOrientation());
//        }
        
        if (MATApplication.mScreenOrientationDefine){
            super.setRequestedOrientation(MATApplication.mScreenOrientation);
        }
        
//        // 只有整机测试和板级测试的屏幕方向需要按配置文件配，单项测试不需要。
//        if (isSystemTest) {
//            String orientationStr = intent.getStringExtra("sd_orientation");
//            if (orientationStr != null) {
//                Log.i("util","orientationStr = " + orientationStr);
//                if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
//                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
//                    super.setRequestedOrientation(orientation);
//                    
//                } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
//                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
//                    super.setRequestedOrientation(orientation);
//                    
//                }
//            } else {
//                // 整机测试中没有配屏幕方向的情况，保持与系统一样的特性
//            }
//        }
    }
    
    protected void initScreenSize() {
        // get screen size
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.widthScreen = dm.widthPixels;
        this.heightScreen = dm.heightPixels;
        
    }
    
    protected void initLenXY() {
        // TODO 动态获取 状态栏高度，标题高度
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
//            lenX = widthScreen / 2;
//            lenY = (heightScreen - (50 + 25 + 20)) / 3;
            lenX = widthScreen / 2;
            lenY = (heightScreen-40) / 3;
        } else {
//            lenX = widthScreen / 3;
//            lenY = (heightScreen - (50 + 25 + 10)) / 2;
            lenX = widthScreen / 3;
            lenY = (heightScreen -40 ) / 2;
        }
    }
    
    protected void initView() {

        mSucBtn = (Button) findViewById(R.id.success_button);
        mFailBtn = (Button) findViewById(R.id.fail_button);
        mRepeatBtn = (Button) findViewById(R.id.repeat_button);

        mSucBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = true;
                finish();
            }
        });

        attachOnTouchListener(mSucBtn);

        mFailBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
            }
        });
        
        attachOnTouchListener(mFailBtn);

        mRepeatBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                BaseActivity.this.recreate();
            }
        });
        
        attachOnTouchListener(mRepeatBtn);
        mItemTestFinish = false;
    }
    
    protected void attachOnTouchListener(Button btn) {
        if (btn == null) return;
        btn.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    v.setBackgroundColor(Color.argb(255, 255, 255, 102));
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    v.setBackgroundColor(Color.argb(255, 255, 255, 255));
                }
                return false;
            }
        });
    }
    
    private void initTestCase() {
        tc = LogWriter.TestCase.getSingletonInstanse(test_pos, itemName, "", is_pass);
    }
    
    protected void setTestResult (boolean isLogSuc) {
        Intent data = new Intent();
        data.putExtra(TEST_ITEM, test_pos);
        data.putExtra(TEST_ITEM_RESULT, is_pass);
        data.putExtra(TEST_LOG_RESULT, isLogSuc);
        data.putExtra(LogWriter.LogFileNameTag, logFileName);
        setResult(0, data);
    }
    
    public void SetResult(boolean bResult)
    {
        is_pass = bResult;
    }
    
    protected void setTestResult () {
        Intent data = new Intent();
        data.putExtra(TEST_ITEM, test_pos);
        data.putExtra(TEST_ITEM_RESULT, is_pass);
        setResult(0, data);
    }
    
    @Override
    public void finish() {
//        System.out.println("tangjun BaseActivity is finishing...");
        boolean isLogSuc = true;
//        try {
//            // new feature V2.1.8: all of test need record log
//            if (!isLogged /*&& isSystemTest*/) {
////                System.out.println("tangjun activity finish. logFileName=" + logFileName);
//                LogWriter.write(logFileName, tc);
//            }
//        } catch (IOException e) {
//            isLogSuc = false;
//        } finally {
            setTestResult(isLogSuc);
//        }
        super.finish();
    }

    protected boolean checkErrorResult(int expect, int actual, int error) {
         expect = Math.abs(expect);
         actual = Math.abs(actual);
         error = Math.abs(error);
         return Math.abs(expect - actual) <= error;
     }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        switch (keyCode) {
//        case KeyEvent.KEYCODE_BACK:
//            //if (isSystemTest) {
//            if (FactoryTest.getIsTestAll()){
//                return true;
//            }
//        default:
//            break;
//        }

        switch(keyCode){
           case KeyEvent.KEYCODE_MENU:
               Log.d(TAG, " the key is menu key");
                if(mItemTestFinish){
                   is_pass = true;
                   finish();
                }
               return false;
           case KeyEvent.KEYCODE_BACK:
               Log.d(TAG, " the key is back key");
               if(mItemTestFinish){
                is_pass = false;
                finish();
               }
               return false;
           }

        return super.onKeyDown(keyCode, event);
    }
    
    protected void changeLanguage(Locale locale) {
        //应用内配置语言
        Resources resources =getResources();//获得res资源对象  
        Configuration config = resources.getConfiguration();//获得设置对象  
        DisplayMetrics dm = resources.getDisplayMetrics();//获得屏幕参数：主要是分辨率，像素等。
        config.locale = locale;
        resources.updateConfiguration(config, dm);
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Resources resourse = this.getResources();
        Configuration config = resourse.getConfiguration();
        SharedPreferences pre = getSharedPreferences(MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
//        System.out.println("tangjun preference lan = " + lanPre);
        if (lanPre.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        Locale.setDefault(config.locale);
        this.getBaseContext().getResources().updateConfiguration(config, resourse.getDisplayMetrics());
    }
    
    protected void updateConfiguration() {
        Resources resourse = this.getResources();
        Configuration config = resourse.getConfiguration();
        SharedPreferences pre = getSharedPreferences(MATApplication.LANGUAGE_PREF, Context.MODE_PRIVATE);
        String lanPre = pre.getString(MATApplication.LANGUAGE_KEY, "zh");
//        System.out.println("tangjun preference lan = " + lanPre);
        if (lanPre.equals("zh")) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            config.locale = Locale.ENGLISH;
        }
        Locale.setDefault(config.locale);
        this.getBaseContext().getResources().updateConfiguration(config, resourse.getDisplayMetrics());
    }
    
    protected void initProductType() {
        PropertiesConfParser propParser = (PropertiesConfParser) ConfigFileParseUtil.getConfParserConcrete(this, AConfigFileParser.EXTENSION_PROPERTISE);
        PropertiesUtil properties = propParser.getProperties(isPcba);
        String proTypeStr = properties.getProperty(PropertiesConstants.KEY_PRODUCT, "1");
        try {
            productType = Integer.valueOf(proTypeStr);
        } catch (NumberFormatException e) {
            productType = PropertiesConstants.VALUE_PRODUCT_SOFIA; // default: [1] SoFIA
        }
    }
    
    protected boolean isSoFIAProduct() {
//        return productType == PropertiesConstants.VALUE_PRODUCT_SOFIA;
        return MATApplication.iProductType == PropertiesConstants.VALUE_PRODUCT_SOFIA;
    }
    

}
